﻿using DoNetDrive.AspWebSocke;
using DoNetDrive.Core.Packet;
using DotNetty.Buffers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Face8280WebSocketServer.Command
{
    public class JsonPacketDecompile : INPacketDecompile
    {
        public bool Decompile(IByteBuffer buf, List<INPacket> retPacketList)
        {
            try
            {
                int buflen = buf.ReadableBytes;
                var len = buf.ReadInt();
                if (len == 0 && len > buflen)
                {
                    return false;
                }
                var offset = buf.ArrayOffset + buf.ReaderIndex;
                var sJson = JsonPacket.JsonEncoding.GetString(buf.Array, offset, len);
                buf.SetReaderIndex(buf.ReaderIndex+len);
                byte[] files = null;
                if (buf.ReadableBytes > 0)
                {
                    files = new byte[buf.ReadableBytes];
                    buf.ReadBytes(files);
                }
                else if (buf.ReadableBytes < 0)
                {
                    Console.WriteLine("buf长度小于0");
                }
                retPacketList.Add(new JsonPacket(sJson, files));
               
            }
            catch (Exception ex)
            {
                retPacketList.Add(new JsonPacket("解析数据异常:"+ex.Message));
                //return true;
            }
            return true;
        }

        public void Dispose()
        {

        }
    }
}
